package planner.domain;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;


public class Domain {
	
	private final boolean debug = false;
	
	private ArrayList<Operator> operators;
	
	public Domain(String fileName){
		operators = new ArrayList<Operator>();
		
		loadDomain(fileName);

		printOperators();
	}

		
	private void loadDomain(String fileName){
		SAXBuilder builder = new SAXBuilder();
		try {
			Document doc = builder.build(fileName);			
			Element root = doc.getRootElement();			
			List allElements = root.getChildren();		

			Iterator it = allElements.iterator();
			
			while(it.hasNext()){
				Element entry = (Element)it.next();
				loadOperator(entry);
			}			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	private void loadOperator(Element op){
		Operator newOp = new Operator(op.getAttributeValue("name"));
		
		List<Element> pcs = op.getChildren("preconditions");		
		Iterator<Element> iPCS = pcs.iterator();
		
		while (iPCS.hasNext()) {
			Element pc =  (Element)iPCS.next();
			newOp.addPrecondition(pc.getValue());
		}
		
		List<Element> es = op.getChildren("effects");
		Iterator<Element> iES = es.iterator();
		
		while (iES.hasNext()) {
			Element e = (Element) iES.next();
			newOp.addEffect(e.getValue());
		}
		
		operators.add(newOp);
	}
	
	private void printOperators(){
		debug("Operators Loaded");
		
		Iterator<Operator> iOps = operators.iterator();
		
		while (iOps.hasNext()) {
			Operator operator = (Operator) iOps.next();
			operator.printOperator(debug);
		}
	}
	
	public ArrayList<Operator> getOperators(){
		return operators;
	}
	
	private void debug(String text){
		if(debug)
			System.out.println(text);
	}
}
